import {
  asyncRoutes,
  constantRoutes,
  wildcardRoutes
} from '@/router';

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

function setRedirect(routes) {
  routes.forEach(r => {
    if (r.children && r.children.length > 0) {
      for (let i = 0; i < r.children.length; i++) {
        if (r.children[i].path.indexOf('/:') === -1) {
          r.redirect = r.path + '/' + r.children[i].path;
          break;
        }
      }
    }
  });
}

export function filterAsyncRoutes(routes, menusObj, parentPath = '') {
  if (process.env.VUE_APP_DISABLE_AUTH === '1') return asyncRoutes;
  let res = [];
  routes.forEach(route => {
    const tmp = {
      ...route
    };
    let fullPath = parentPath + tmp.path;
    if (
      menusObj.hasOwnProperty(fullPath) ||
      menusObj.hasOwnProperty(tmp.redirect) ||
      route.internal
    ) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(
          tmp.children,
          menusObj,
          fullPath + '/'
        );
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  routes: [],
  addRoutes: [],
  btnAuth: []
};

const orderedOrigin = [
  '项目生命周期管理', '待办事项', '商机项目库', '订单项目库', '风险项目自检', '事业部目标管理', '登录人员管理',
];

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;

    const hiddenMenus = constantRoutes
      .concat(routes)
      .filter(item => item.hidden === true);
    let commonMenus = constantRoutes
      .concat(routes)
      .filter(item => item.hidden !== true);
    let orderedMenus = [];

    for (let i = 0; i < orderedOrigin.length; i++) {
      let match = commonMenus.find(
        item => item.meta.title === orderedOrigin[i]
      );

      if (match) {
        orderedMenus.push(match);

        commonMenus = commonMenus.filter(
          item => item.meta.title !== match.meta.title
        );
      }
    }

    const finals = hiddenMenus.concat(orderedMenus).concat(commonMenus);

    state.routes = finals;
  },
  SET_BTN_AUTH: (state, auth) => {
    state.btnAuth = auth;
  }
};

function getFirstLeaf(nodes, pathArr) {
  let firstNode = nodes[0];
  if (firstNode.children && firstNode.children.length > 0) {
    pathArr.push(firstNode.path);
    getFirstLeaf(firstNode.children, pathArr);
  } else {
    pathArr.push(firstNode.path);
  }
  return pathArr;
}

const actions = {
  generateRoutes({
    state,
    commit
  }, menus) {
    return new Promise((resolve, reject) => {
      let accessedRoutes;
      let menusIndexObj = {};
      let btnAuth = [];
      menus.forEach(item => {
        if (item.menuUrl) {
          let urlArr = item.menuUrl.split(',');
          urlArr.forEach(url => {
            let path = '';
            let pageArr = url.match(/\/[^\/]+/g); //匹配 /xxx
            if (pageArr) {
              pageArr.forEach(page => {
                path += page;
                menusIndexObj[path] = item;
              });
            }
          });
          // if(item.type === 2){
          //   btnAuth.push(item.menuUrl)
          // }
          if (item.type === 2) {
            let menuFilter = menus.filter(
              menu => menu.authorityId === item.parentId
            );
            if (menuFilter.length > 0) {
              btnAuth.push(menuFilter[0].menuUrl + '{' + item.menuUrl + '}');
            }
          }
        }
      });
      let enableRoutes = filterAsyncRoutes(asyncRoutes, menusIndexObj);
      let rootPath = '';
      if (enableRoutes.length > 0) {
        rootPath = getFirstLeaf(enableRoutes, []).join('/');
        setRedirect(enableRoutes);
      }
      accessedRoutes = [{
        path: '/',
        redirect: rootPath,
        hidden: true
      }].concat(
        enableRoutes,
        wildcardRoutes
      );
      commit('SET_ROUTES', accessedRoutes);
      commit('SET_BTN_AUTH', btnAuth);
      resolve(accessedRoutes);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
